package org.jeecg.modules.wms.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.wms.service.ISurplusMaterialService;
import org.jeecg.modules.wms.vo.SurplusMaterialVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;

/**
 * 余料管理控制器
 */
@Slf4j
@Api(tags = "余料管理")
@RestController
@RequestMapping("/wms/surplusMaterial")
public class SurplusMaterialController {
    
    @Autowired
    private ISurplusMaterialService surplusMaterialService;
    
    /**
     * 根据订单ID获取余料信息
     */
    @AutoLog(value = "余料管理-根据订单ID获取余料信息")
    @ApiOperation(value = "余料管理-根据订单ID获取余料信息", notes = "余料管理-根据订单ID获取余料信息")
    @GetMapping("/getByOrderId")
    public Result<List<SurplusMaterialVO>> getSurplusMaterialsByOrderId(
            @RequestParam(name = "orderId", required = true) String orderId) {
        try {
            log.info("查询订单[{}]的余料信息", orderId);
            List<SurplusMaterialVO> surplusMaterials = surplusMaterialService.getSurplusMaterialsByOrderId(orderId);
            
            // 处理和分组余料
            List<SurplusMaterialVO> groupedMaterials = surplusMaterialService.processAndGroupSurplusMaterials(surplusMaterials);
            //根据余料编号进行字符串排序
            groupedMaterials.sort(Comparator.comparing(SurplusMaterialVO::getMaterialCode));
            return Result.OK(groupedMaterials);
        } catch (Exception e) {
            log.error("查询订单[{}]的余料信息失败", orderId, e);
            return Result.error("获取余料信息失败: " + e.getMessage());
        }
    }
} 